package org.sdp.pearproject.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.sdp.pearproject.dao.domain.Criterion;
import org.sdp.pearproject.dto.request.*;
import org.sdp.pearproject.utils.JavaBeansUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.ConcurrentReferenceHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class BaseServiceImpl {
    public static Map<String, String> beanClassNameMap = new ConcurrentReferenceHashMap<>();
    public static Map<String, String> listMethodNameMap = new ConcurrentReferenceHashMap<>();
    public static Map<String, String> listMethodParameterClassNameMap = new ConcurrentReferenceHashMap<>();
    public static Map<String, String> updateMethodNameMap = new ConcurrentReferenceHashMap<>();
    public static Map<String, String> updateMethodParameterClassNameMap = new ConcurrentReferenceHashMap<>();

    @Autowired
    protected HttpServletRequest httpServletRequest;

    @Autowired
    protected HttpServletResponse httpServletResponse;

    public void fixRequest(String module, String method, Object request) throws Exception {
        fixRequest(module, method, request, null);
    }

    public void fixRequest(String module, String method, Object request, Object record) throws Exception {
        if (request instanceof BaseRequest) {
            BaseRequest baseRequest = (BaseRequest)request;
            baseRequest.checkParam();
        }
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        httpServletResponse.setHeader("server_tsp", datetimeFormat.format(new Date()));
    }

    public boolean needCheckDeleteList(BaseRequest request) {
        return false;
    }

    public void checkNonNull(Object object, String remark) throws Exception {
        if (object == null) {
            throw new Exception("param is null:"+remark);
        }
    }

    public void checkResult(String module, String method, BaseRequest request) throws Exception {
        checkResult(module, method, request, null);
    }

    public void checkResult(String module, String method, BaseRequest request, Object result) throws Exception {

    }

    public void clearPageInfo(BaseRequest request) {
        if(request.getQueryOptions() != null) {
            request.getQueryOptions().remove("count");
            request.getQueryOptions().remove("limit");
        }
        request.setPageNo(null);
        request.setPageSize(null);
    }

    public void fixRequest(String tableName, String method, BaseRequest request) throws Exception {

    }

    public void assertNotNull(Object obj, String title) throws Exception {
        if (obj == null) {
            throw new Exception(title + " is null");
        }
    }

    public Exception createFailException(String msg) {
        return new Exception(msg);
    }

    public void copyProperties(Object source, Object target) throws Exception {
        JavaBeansUtil.copyProperties(source, target);

    }

    public void fixEqualCondition(BaseRequest request, String module, String method, String fieldName, List<Criterion> criteria) {
    }

    public void checkInternalId(BaseRequest request, String module, String method, Object id) {

    }

    public Exception checkDBDupException(Exception ex, Map<String, String> map) throws Exception {
        String exMessage = ex.getMessage();
        Integer dupIndex = exMessage.indexOf("Duplicate entry '");
        Integer forKeyIndex = exMessage.indexOf("' for key ", dupIndex);
        if (dupIndex >= 0 && forKeyIndex >= 0) {
            String errInfo = exMessage.substring(dupIndex + "Duplicate entry '".length(), forKeyIndex);
            String keyName = exMessage.substring(forKeyIndex + 1).split("'")[1];
            if (map.containsKey(keyName)) {
                return new Exception("已经存在：" + errInfo + "(" + map.get(keyName) + ")");
            }
        }
        return new Exception(ex.getMessage());
    }

    public Exception createFailException(Exception ex) {
        if (ex instanceof DuplicateKeyException || ex.getMessage().indexOf("Duplicate entry") >= 0) {
            return new Exception(ex.getMessage().split("SQL:")[0]);
        } else {
            return new Exception(ex.getMessage());
        }
    }

    public void addHistory(BaseRequest request, String op, String type, String info, Object keyId, String keyName) {
    }

    public Exception createUpdateFailException() {
        return new Exception("update fail");
    }

    public Exception createDatabaseFailException(Exception ex) {
        ex.printStackTrace();
        String msg = ex.getMessage().split(" error")[0];
        if (msg.length() > 200) {
            msg = msg.substring(0, 200);
        }
        return ex;
    }
}
